package com.hwk.test;

/**
 * 斐波那契数
 * 0 1 1 2 3 5 8
 */
public class Main {
    /**
     * 递归实现
     * @param n
     * @return
     * O(2^n)
     */
    public static int fib1(int n){
        if(n<3){
            return n-1;
        }else{
            return fib1(n-1)+fib1(n-2);
        }
    }

    /**
     * 循环实现
     * @param n
     * @return
     * O(n)
     */
    public static int fib2(int n){
        if(n<3){
            return n-1;
        }else {
            int first=0;
            int second = 1;
            for (int i = 1; i < n-1; i++) {
                second = first+second;
                first = second-first;
            }
            return second;
        }
    }

    public static void main(String[] args) {
        int fib1 = Main.fib1(20);
        int fib2 = Main.fib2(20);
        System.out.println(fib1);
        System.out.println(fib2);
    }
}
